package hiatao.puzzle.utils;

import hiatao.puzzle.inter.SaveImageCallback;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class FileUtils {

	/**
	 * 
	 * @param extension 后缀名 如".jpg"
	 * @return
	 */
	public static String createFileNmae(String extension){
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss",Locale.getDefault());
		// 转换为字符串
		String formatDate = format.format(new Date());
		//查看是否带"."
		if(!extension.startsWith("."))
			extension="."+extension;
		return formatDate+extension;
	}
	/**
	 * 
	 * @param 
	 * @return
	 */
	public static String getCameraPath(){
		String path =Environment.getExternalStorageDirectory()+"/DCIM/Camera/";
		File folder=new File(path);
		if(!folder.exists()){
			folder.mkdirs();
		}
		return path;
	}
	/**
	 * 
	 * @param 
	 * @return
	 */
	public static String getAppPath(){
		String path =Environment.getExternalStorageDirectory()+"/Android/data/haitao.puzzle/";
		File folder=new File(path);
		if(!folder.exists()){
			folder.mkdirs();
		}
		return path;
	}
	
	public static void  saveFileNewThread(final Context context,byte[] data,final SaveImageCallback callback){

		if(data!=null){
			final String name = FileUtils.createFileNmae(".jpg");
			final Bitmap bm=BitmapFactory.decodeByteArray(data, 0, data.length);
			File file=new File(FileUtils.getCameraPath()+name);  
			try{
				FileOutputStream fos=new FileOutputStream(file);
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);//
				fos.write(bos.toByteArray());
				fos.flush();
				fos.close();
				// 子线程中操作
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						float c_width = bm.getWidth();
						float c_height =bm.getHeight();
						
						if(c_width>c_height){
							c_width = bm.getHeight();
							c_height =bm.getWidth();
						}
/*							int w = bm.getWidth(); // 得到图片的宽，高
						int h = bm.getHeight();
						float p_width = mContainer.getPreviewSize().width;
						float p_height =mContainer.getPreviewSize().height;
						
						if(p_width>p_height){
							p_width = mContainer.getPreviewSize().height;
							p_height =mContainer.getPreviewSize().width;
						}
						int widthCut=(int) ((c_width-p_width)/2);
						int heightCut=(int) ((c_height-p_height)/2+(p_height*((float)PixelUtil.dp2px(CameraAty.this, 50)/(PixelUtil.getScreenHeight(CameraAty.this)))));
						int heightCut=(int)(bm.getHeight()*((float)PixelUtil.dp2px(CameraAty.this, 50)/(PixelUtil.getScreenHeight(CameraAty.this))));
						Bitmap bitmap  = BitmapCut.ImageCrop(heightCut,widthCut,bm,true,(int)p_width);*/
						int heightCut=(int) (c_height *((float)PixelUtil.dp2px(context, 50)/(PixelUtil.getScreenHeight(context))));
						Bitmap bitmap  = BitmapCut.ImageCrop(heightCut,bm,true);
						BitmapSaveUtils.saveBmpToSd(FileUtils.getAppPath(), bitmap, name,100);
						System.out.println("save---------------->");
						if(callback!=null){
							callback.saveResult(true,FileUtils.getAppPath()+name);
						}
					}
				}).start();
			}catch(Exception e){
				if(callback!=null){
					callback.saveResult(false,null);
				}
			}
		}else{
			if(callback!=null){
				callback.saveResult(false,null);
			}
		}
		
	}
	
	public static void  saveFileNewThread(final Context context,final Bitmap bitmap,final int maxSize,final SaveImageCallback callback){
		
		final String name = FileUtils.createFileNmae(".jpg");
		final String path = FileUtils.getAppPath()+name;
		final File file=new File(path);  
		//产生新的文件名 
			//存图片大图
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					FileOutputStream fos;
					fos = new FileOutputStream(file);
					ByteArrayOutputStream bos=compress(bitmap,maxSize);
					fos.write(bos.toByteArray());
					fos.flush();
					fos.close();
					//return path; 
					if(callback!=null){
						callback.saveResult(true,path);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
			
		
	
	}
	/**
	 * 图片压缩方法
	 * @param bitmap 图片文件
	 * @param max 文件大小最大值
	 * @return 压缩后的字节流
	 * @throws Exception
	 */
	public static ByteArrayOutputStream compress(Bitmap bitmap,int maxSize){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 99;
		while ( baos.toByteArray().length / 1024 > maxSize) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			options -= 3;// 每次都减少10
			//压缩比小于0，不再压缩
			if (options<0) {
				break;
			}
			//Log.i(TAG,baos.toByteArray().length / 1024+"");
			baos.reset();// 重置baos即清空baos
			bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
		}
		return baos;
	}
	public static double getDirSize(File file) {
		// 判断文件是否存在
		if (file.exists()) {
			// 如果是目录则递归计算其内容的总大小
			if (file.isDirectory()) {
				File[] children = file.listFiles();
				double size = 0;
				for (File f : children)
					size += getDirSize(f);
				return size;
			} else {// 如果是文件则直接返回其大小,以“兆”为单位
				double size = (double) file.length() / 1024 / 1024;
				return size;
			}
		} else {
			return 0.0;
		}
	}
	public static double getDirSize(String path) {
		if(path==null){
			return 0.0;
		}
		else{
			return getDirSize(new File(path));
		}
	}


	/** 删除文件 **/
	public static boolean deleteFile(File f) {

		if (f.isDirectory()) {
			File[] files = f.listFiles();
			if (files != null && files.length > 0) {
				for (int i = 0; i < files.length; ++i) {
					deleteFile(files[i]);
				}
			}
		}
		return f.delete();
	}
	/** 删除文件 **/
	public static boolean deleteFile(String path ) {
		
		if(path==null){
			return false;
		}
		else{
			return deleteFile(new File(path));
		}
	}

}
